<?php
            define('ACC', true);
require('./include/init.php');

session_start(); 
//print_r($_SESSION);
$userid = $_SESSION['user_id'];

//$userid = 26;

$company = new companymodel();
$companyinfo = $company->getcompanyinfo($userid);
$companyid = $companyinfo['company_id'];
$company_y = $companyinfo['company_y'];
$company_q = $companyinfo['company_q'];

$purchaseinfo = $_POST; 
$purchasebuildingmsg = '';



if(!empty($purchaseinfo)){
    foreach($purchaseinfo as $k=>$v){
        if(($v!='')&&($v!='0')){
            $elementname = $company->getelementname($k);
            $succeed = $company->actionpurchasebuilding($companyid, $k, $v);
            if($succeed === false){
                $purchasebuildingmsg = $purchasebuildingmsg . '投资建设' . $v . '个' .$elementname . '失败，因为资金不足。<br/>';
            }else{
                $purchasebuildingmsg = $purchasebuildingmsg . '投资建设' . $v . '个' .$elementname . '成功。<br/>';
            }
        }    
    }
    
    $cashequivalent = $company->getcash_equivalent($companyid); 
    $totalcashequivalent = 0;
    foreach($cashequivalent  as $k=>$v){
        $totalcashequivalent = $totalcashequivalent + $v;
    }
    
    $buildinginfo = $company->getallelements($companyid, 'building');  
    $buildinglist = $company->getelementlist('building');
    $building = array();
    $purchaselimit = array();
    
    foreach($buildinglist  as $k=>$v){
        $elementid = $v['element_id'];    
        $numofbuilding = 0;
        $buildingprice =  $v['building_price'];
        foreach($buildinginfo as $key =>$value){
             if($value['element_id'] == $v['element_id']){
                  $numofbuilding++;
                   } 
        }
        $building[$elementid] =  $numofbuilding;
        $purchaselimit[$elementid] =  floor($totalcashequivalent / $buildingprice);
    }
    
    echo "
    { \"purchasebuildingmsg\" : \"{$purchasebuildingmsg}\" , 
      \"totalcashequivalent\" : \"{$totalcashequivalent}\"";
      
    foreach($building as $k=>$v){
        echo ',
"numof' . $k . '" : "' . $v . '"'; 
    }
    
    foreach($purchaselimit as $k=>$v){
        echo ',
"limitof' . $k . '" : "' . $v . '"'; 
    }
      
    echo '
    }
    ';
    
}
 
?>
